const Koa = require("koa")
const consola = require("consola")
const { Nuxt, Builder } = require("nuxt")
const app = new Koa()
const config = require("../nuxt.config")
const routers = require("./routers")
require("./db")()

async function start() {
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || "0.0.0.0",
    port = process.env.PORT || 3000
  } = nuxt.options.server

  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  routers(app)

  app.use(async function(ctx, next) {
    let isApi = /api\//.test(ctx.request.url)
    if (isApi) {
      await next()
    } else {
      ctx.status = 200
      ctx.respond = false
      ctx.req.ctx = ctx
      return new Promise((resolve, reject) => {
        ctx.res.on("close", resolve)
        ctx.res.on("finish", resolve)
        nuxt.render(ctx.req, ctx.res, promise => {
          promise.then(resolve).catch(reject)
        })
      })
    }
  })

  app.listen(port, host)

  consola.ready({
    message: `Server listening on http://${host}:${port}`
  })
}
start()
